package com.escom.activity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.escom.R;
import com.escom.healthlc.entidad.PositionORM;
import com.escom.service.PositionService;
import com.escom.utils.Constantes;

import java.util.Observable;
import java.util.Observer;

/**
 * Created by Carlos on 21/04/2014.
 */
public class PositionFragment extends Fragment {

    private SharedPreferences sharedpreferences;
    private ImageView imageView;
    private PositionORM position;
    private static Thread tareaPosition;

    private class PositionObservador implements Observer {

        @Override
        public void update(Observable o, Object arg) {
            if(position != null && position.getPosition() != null) {
                if (position.getPosition().equals("1")) {
                    imageView.setImageResource(R.drawable.sc_boca_arriba);
                } else if (position.getPosition().equals("2")) {
                    imageView.setImageResource(R.drawable.sc_izquierdo);
                } else if (position.getPosition().equals("3")) {
                    imageView.setImageResource(R.drawable.sc_derecho);
                } else if (position.getPosition().equals("4")) {
                    imageView.setImageResource(R.drawable.sc_boca_abajo);
                } else if (position.getPosition().equals("5")) {
                    imageView.setImageResource(R.drawable.sc_pie);
                } else {
                    imageView.setImageResource(R.drawable.sc_boca_abajo);
                }
            }else{
                Log.d(Constantes.LOG_ID, this.getClass().getName() + " Position NULL");
            }
        }
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View viewActivity = inflater.inflate(R.layout.fragment_position, container, false);
        imageView = (ImageView) viewActivity.findViewById(R.id.iViewPositionImage);

        if (tareaPosition != null && tareaPosition.isAlive()){
            //Log.d(Constantes.LOG_ID, this.getClass().getName() + " El hilo ya existe");
        }else{
            position = new PositionORM();
            PositionObservador positionObservador = new PositionObservador();
            PositionService positionService = new PositionService(position, getActivity());
            positionService.addObserver(positionObservador);
            tareaPosition = new Thread(positionService);
            tareaPosition.start();
            //Log.d(Constantes.LOG_ID, this.getClass().getName() + " Se inicio el hilo");
        }
        return viewActivity;
    }

}
